package com.snda.dsync;

import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileType;
import org.apache.commons.vfs.FileTypeSelector;
import org.apache.commons.vfs.VFS;

public class VFSPusher {
	private Log log = LogFactory.getLog(VFSPusher.class);

	public boolean push(FileObject from, FileObject to, FileObject tmpdir,
			boolean override) {
		log.info("push " + from + " to " + to + " begin");
		try {
			if (!from.exists()) {
				log.info("push " + from + " to " + to
						+ " ,from file not exists");
				return true;
			}
			if (to.exists()) {
				if (!override) {
					log.info("push " + from + " to " + to
							+ " ,to file exists and not override");
					return true;
				} else {
					if (from.getContent().getSize() == to.getContent()
							.getSize()) {
						log.info("push " + from + " to " + to
								+ " ,to file exists but size equal");
						return true;
					}
				}
			}
			FileObject tempF = getTempFile(tmpdir);
			tempF.copyFrom(from, new FileTypeSelector(FileType.FILE));
			to.getParent().createFolder();
			if (to.exists())
				to.delete();
			tempF.moveTo(to);
			if (to.exists()) {
				log.info("push " + from + " to " + to + " success");
				return true;
			} else {
				log.info("push " + from + " to " + to + " fail");
				return false;
			}
		} catch (FileSystemException e) {
			log.warn("push " + from + " to " + to + " fail");
			e.printStackTrace();
			return false;

		}
	}

	protected FileObject getTempFile(FileObject tmpdir)
			throws FileSystemException {
		if (!tmpdir.exists())
			tmpdir.createFolder();
		FileObject tmp = null;
		while (tmp == null || tmp.exists()) {
			tmp = VFS.getManager().resolveFile(tmpdir,
					"tmp_" + UUID.randomUUID().toString());
		}
		return tmp;

	}
}
